#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

#define COM_SIZE 1024
char command[COM_SIZE];

char* NowDir(char** env){
  char* path = NULL;
  for(int i = 0; env[i]; ++i){
    if(env[i][0] == 'P'
        && env[i][1] == 'W'
        && env[i][2] == 'D'){
      path = env[i];
      break;
    }
  }
  char *prev, *cur;
  prev = cur = path;
  while(*cur){
    if(*cur == '/'){
      prev = cur;
    }
    ++cur;
  }
  return prev;
}

int RecvCommand(char* dir){
  memset(command, 0, COM_SIZE);
  printf("[MyShell %s]$ ", dir);
  fflush(stdout);
  if(fgets(command, COM_SIZE, stdin) == NULL){
    perror("fgets");
    return -1;
  }
  return 0;
}

char** SplitCommad(){
  static char* argv[64];
  int argc = 0;
  char* cur = command;
  while(*cur){
    if(!isspace(*cur)){
      argv[argc++] = cur;
      while(*cur && !isspace(*cur)){
        ++cur;
      }
      continue;
    }
    *cur++ = '\0';
  }
  argv[argc] = NULL;
  return argv;
}

void DealCommad(char* const* env){
  char** argv = {NULL};
  int pid = fork();
  if(pid < 0){
    perror("fork");
    exit(0);
  }
  else if(pid == 0){
    argv = SplitCommad();
    if(argv[0] == NULL){
      printf("你输了个啥?\n");
      exit(0);
    }
    if(execvpe(argv[0], argv, env) < 0){
      printf("你输的是个啥?: ");
      for(int i = 0; argv[i]; ++i){
        printf("%s", argv[i]);
      }
      printf("\n"); 
    }
  }
  else{
    wait(NULL);
  }
}

int main(){
  extern char** environ;
  char* Dir = NowDir(environ);
  ++Dir;
  while(1){
    if(RecvCommand(Dir) < 0){
      continue;
    }
    DealCommad(environ);
  } 
  return 0;
}
